const connection = require('../app/databases');

class AccountService {
  // 账户登录
  async accountLogin(username, password) {
    try {
      const statement = `SELECT * FROM account WHERE name = ?;`;
      const [result] = await connection.execute(statement, [username]);
      
      if (result.length) {
        const dataPassword = result[0].password;

        if (password != dataPassword) {
          return '密码错误！'
        } else {
          return {
            username,
            password
          };
        }
      } else {
        console.log('用户名错误或不存在！');
        return '用户名错误或不存在！';
      }
    } catch (error) {
      return error.message;
    }    
  }

  // 账户注册
  async accountRegister(username, password) {
    try {
      const statement1 = `SELECT * FROM account WHERE name = ?;`;
      const [result] = await connection.execute(statement1, [username]);

      if (!result.length) {
        const statement2 = `INSERT INTO account (name, password) VALUES (?, ?) `;
        const [result] = await connection.execute(statement2, [username, password]);

        return 'success';
      } else {
        return '用户名已存在，请重新输入！'
      }
      
    } catch (error) {
      return error.message;
    }    
  }
}

module.exports = new AccountService();